package com.o.mj.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;

public class RedisSubscribeConfig {
    /**
     * 该方法用于发布消息，这里指定两个参数的意思是：向某个频道发布某些消息
     * 使用静态方法，方便调用
     * @param channel
     * @param message
     */
    public static void publishMessage(String channel,String message) {
        Jedis jedis=new Jedis("172.16.201.222",6379);
        jedis.auth("123456");
        try {
            jedis.publish(channel,message);
        }catch (Exception e) {
            System.out.println(e.getMessage());
        }finally {
            jedis.close();
        }
    }

    /**
     * 该方法用于接受消息，调用之后，会一直执行下去
     * 当有发布对应消息时，会在jedisPubSub中接收到！！！
     * @param channel
     */
    public static void subscribeMessage(String channel) {
        Jedis jedis=new Jedis("172.16.201.222",6379);
        jedis.auth("123456");
        new Thread(()->{
            try {
                jedis.subscribe(jedisPubSub,channel);
            }catch (Exception e) {
                System.out.println(e.getMessage());
            }finally {
                jedis.close();
            }
        }).start();
    }

    /**
     * 这里使用内部类JedisPubSub
     * 对 接收消息、订阅频道、取消订阅频道 三个方法进行重写
     */
    public static JedisPubSub jedisPubSub=new JedisPubSub() {
        @Override
        public void onMessage(String channel, String message) {
            System.out.println("此时收到了" + channel + "频道发来的消息：" + message);
            System.out.println(channel + "：" + message);
        }

        @Override
        public void onSubscribe(String channel, int subscribedChannels) {
            System.out.println("此时订阅了" + channel + "频道");
            System.out.println(channel + "：" + subscribedChannels);
        }

        @Override
        public void onUnsubscribe(String channel, int subscribedChannels) {
            System.out.println("此时取消订阅了" + channel + "频道");
            System.out.println(channel + "：" + subscribedChannels);
        }
    };

}
